package com.fsh.wx.handler;

import com.fsh.wx.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ReceiveTextMsgHandler implements WxChatMsgHandler{

    @Resource
    private RedisUtil redisUtil;

    private static final String KEY_WORD = "验证码";
    private static final String LOGIN_CODE="loginCode";

    /**
     * 获取枚举类型，是用来干什么的
     */
    @Override
    public WxChatMsgTypeEnum getMsgType() {
        return WxChatMsgTypeEnum.TEXT_MSG;
    }

    /**
     * 处理各自的业务逻辑
     *
     * @param messageMap
     */
    @Override
    public String dealMsg(Map<String, String> messageMap) {
        log.info("接收到文本消息事件");

        String fromUserName = messageMap.get("FromUserName");
        String toUserName = messageMap.get("ToUserName");
        String content = messageMap.get("Content");
        String replyContent="";
        if(KEY_WORD.equals(content)){
            Random random=new Random();
            //随机6位验证码
//            int num=random.nextInt(100000)+100000;
            int num = random.nextInt(1000);
            replyContent=String.valueOf(num);

            //存入redis中,5分钟有效期 。  key为 验证码,value就是 openid（fromUserName）。
            //因为 我们需要通过  前端填写的验证码 来 获取 openid
            String codeKey = redisUtil.buildKey(LOGIN_CODE,replyContent);
//            redisUtil.setNx(codeKey,fromUserName,5L, TimeUnit.MINUTES);
            redisUtil.setNx(codeKey,fromUserName,5L, TimeUnit.HOURS);

        }else{
            replyContent="unknown";
        }
        String reply="<xml>\n" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
                "  <CreateTime>12345678</CreateTime>\n" +
                "  <MsgType><![CDATA[text]]></MsgType>\n" +
                "  <Content><![CDATA["+replyContent+"]]></Content>\n" +
                "</xml>";

        return reply;
    }
}
